package repository;

import java.io.File;
import java.io.IOException;
import java.util.Locale;
import java.util.Objects;

import fileoperation.FileCreation;
import fileoperation.FileDeletion;
import gitobject.JitIndex;
import gitobject.Tree;

/**
 * Todo: Add your own code. JitInit.init("worktree") should be able to create a repository "worktree/.jit" ,
 *       which contains all the default files and other repositories inside. If the repository has
 *       already exists, delete the former one and create a new one. You're welcome to reconstruct the code,
 *       but don't change the code in the core directory.
 */
public class Repository {
    private static String workTree;	//working directory
    private static String gitDir;	//jit repository path

    /**
     * Constructor
     */
    public Repository() throws IOException {
        if(gitDir == ""){
            throw new IOException("The repository does not exist!");
        }
    }
    
    /**
     * Construct a new repository instance with certain path.
     * Constructor
     * @param path
     * @throws IOException
     */
    public Repository(String path) throws IOException {
        workTree = path;
        gitDir = path + File.separator + ".jit";
    }

    public static String getGitDir() {
        return gitDir;
    }

    public static String getWorkTree() {
        return workTree;
    }
    
    /**
     * Helper functions.
     * @return
     */
    public boolean exist(){ return new File(gitDir).exists(); }

    public boolean isFile(){ return new File(gitDir).isFile(); }

    public boolean isDirectory(){ return new File(gitDir).isDirectory(); }


    /**
     * Create the repository and files and directories inside.
     * @return boolean
     * @throws IOException
     */
    public void createRepo() throws IOException {
    	File folder = new File(workTree + File.separator + ".jit");
    	folder.mkdir();
    	if(System.getProperty("os.name").toLowerCase().equals("windows"))
    	    Runtime.getRuntime().exec("attrib +H " + folder.getAbsolutePath()); //设置为隐藏文件夹
    	String path = workTree + File.separator + ".jit" + File.separator;
    	String[] folderList = {"objects", "refs" + File.separator + "heads", "logs"};
    	String[] fileList = { "HEAD", ".jitConfig"};
        JitIndex index = new JitIndex();
        try {
            index.compressWrite();
        } catch (Exception e) {
            e.printStackTrace();
        }
        FileCreation.createDirectory(path, folderList);
    	for(String item:fileList) {
    	    String text = "";
    		if(Objects.equals(item, "HEAD"))
    		    //使用treeSeparator可以让各种平台统一，实现同样的jit管理不同文件系统的平台
    		    text = "ref: refs" +  Tree.treeSeparator + "heads" + Tree.treeSeparator + "master\n";
    		else if(Objects.equals(item, ".jitConfig"))
    		    text = "name : default\nemail : default@stu.pku.edu.cn\n";
    		FileCreation.createFile(path, item, text);
    	}
    }
}
